package cnblogs.guzb.jaspytdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;

/**
 * @author 顾志兵
 * @mail ipiger@163.com
 * @since 2024-03-25
 */
@SpringBootApplication
public class JaspytDemoAppMain implements CommandLineRunner {

    @Autowired
    Environment env;

    public static void main(String[] args) {
        args = checkOrSetDefaultJasyptPassword(args);
        SpringApplication.run(JaspytDemoAppMain.class, args);
    }

    /**
     * 检查 Jasypt 的密钥设置情况，若未通过命令行传递，则设置默认值
     * @param cmdLineArgs 命令行的参数
     * @return 经过检查后的参数数组
     */
    private static String[] checkOrSetDefaultJasyptPassword(String[] cmdLineArgs) {
        String defaultJasyptPasswordProperty = "--jasypt.encryptor.password=cnblogs";
        if (cmdLineArgs.length == 0) {
            return new String[]{defaultJasyptPasswordProperty};
        }

        if (isCmdLineArgsContainsJasyptPassword(cmdLineArgs)) {
            return cmdLineArgs;
        }

        String[] enhancedArgs = new String[cmdLineArgs.length + 1];
        for (int i = 0; i < cmdLineArgs.length; i++) {
            enhancedArgs[i] = cmdLineArgs[i];
        }
        enhancedArgs[enhancedArgs.length - 1] = defaultJasyptPasswordProperty;
        return enhancedArgs;
    }

    private static boolean isCmdLineArgsContainsJasyptPassword(String[] args) {
        for (String arg : args) {
            if (arg.startsWith("----jasypt.encryptor.password=")) {
                return true;
            }
        }
        return false;
    }


    @Override
    public void run(String... args) throws Exception {
        // 这两个配置，本身就是明文的
        System.out.println("demo-app.username = " + env.getProperty("demo-app.username"));
        System.out.println("demo-app.password = " + env.getProperty("demo-app.password"));

        // 以下两个属性配置项，文件为密文，但PropertySource加载后经过jasypt的处理，变成了明文
        System.out.println("database.username = " + env.getProperty("database.username"));
        System.out.println("database.password = " + env.getProperty("database.password"));
    }
}
